package org.bonorsoft.modules.system.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.bonorsoft.common.api.vo.Result;
import org.bonorsoft.common.aspect.annotation.AutoLog;
import org.bonorsoft.common.aspect.annotation.PermissionData;
import org.bonorsoft.common.constant.UserConstants;
import org.bonorsoft.common.system.base.controller.BonorController;
import org.bonorsoft.modules.system.entity.SysUser;
import org.bonorsoft.modules.system.service.ISysConfigService;
import org.bonorsoft.modules.system.service.ISysDictService;
import org.bonorsoft.modules.system.service.ISysUserService;
import org.bonorsoft.modules.user.entity.Params;
import org.bonorsoft.modules.user.entity.SysUserRole;
import org.bonorsoft.modules.user.service.ISysRoleService;
import org.bonorsoft.modules.user.service.ISysUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;

@Slf4j
@Controller
@RequestMapping("/system/user")
public class SysUserController extends BonorController<SysUser, ISysUserService> {
    private String prefix = "system/user";

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysDictService dictService;

    @Autowired
    private ISysUserRoleService userRoleService;

    @RequiresPermissions("system:user:view")
    @GetMapping()
    public String index()
    {
        return prefix + "/user";
    }

    /**
     * 分页列表查询
     *
     * @param sysUser
     * @param pageNo
     * @param pageSize
     * @param params
     * @return
     */
    @AutoLog(value = "用户-分页列表查询")
    @GetMapping(value = "/list")
    @RequiresPermissions("system:user:list")
    @ResponseBody
    @PermissionData(value = "single", userAlias = "u")
    public Result<?> queryPageList(SysUser sysUser,
                                   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                   Params params,
                                   HttpServletRequest request) {
        Page<SysUser> page = new Page<>(pageNo, pageSize);
        IPage<SysUser> pageList = sysUserService.selectUser(page, sysUser, params, request);
        return Result.ok(pageList);
    }

    /**
     * 新增用户
     */
    @GetMapping("/add")
    public String add(ModelMap mmap)
    {
        mmap.put("roles", roleService.list());
        return prefix + "/add";
    }

    /**
     * 新增保存用户
     */
    @RequiresPermissions("system:user:add")
    @AutoLog(value = "用户管理-新增保存用户")
    @PostMapping("/add")
    @ResponseBody
    public Result<?> add(@Validated SysUser user,
                         @RequestParam(name = "roleIds", required = false) String[] roleIds)
    {
        if (UserConstants.USER_NAME_NOT_UNIQUE.equals(sysUserService.checkUserNameUnique(user.getUsername())))
        {
            return Result.error("新增用户'" + user.getUsername() + "'失败，登录账号已存在");
        }
        else if (UserConstants.USER_PHONE_NOT_UNIQUE.equals(sysUserService.checkPhoneUnique(user)))
        {
            return Result.error("新增用户'" + user.getUsername() + "'失败，手机号码已存在");
        }
        sysUserService.save(user,roleIds);
        return Result.ok("添加成功！");
    }

    /**
     * 修改用户
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, ModelMap mmap)
    {
        SysUser sysUser = sysUserService.getById(id);
        mmap.put("user", sysUser);
        mmap.put("deptName", dictService.queryTableDictTextByKey("sys_dept","dept_name","dept_id",sysUser.getDeptId().toString()));
        mmap.put("roles", roleService.selectRolesByUserId(id));
        return prefix + "/edit";
    }

    /**
     * 修改保存用户
     */
    @RequiresPermissions("system:user:edit")
    @AutoLog(value = "用户管理-修改保存用户")
    @PostMapping("/edit")
    @ResponseBody
    public Result<?> edit(@Validated SysUser user,
                          @RequestParam(name = "roleIds", required = false) String[] roleIds)
    {
        sysUserService.checkUserAllowed(user);
        if (UserConstants.USER_PHONE_NOT_UNIQUE.equals(sysUserService.checkPhoneUnique(user)))
        {
            return Result.error("修改用户'" + user.getUsername() + "'失败，手机号码已存在");
        }
//        else if (UserConstants.USER_EMAIL_NOT_UNIQUE.equals(sysUserService.checkEmailUnique(user)))
//        {
//            return Result.error("修改用户'" + user.getUsername() + "'失败，邮箱账号已存在");
//        }
        sysUserService.updateUser(user, roleIds);
        return Result.ok("编辑成功！");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "用户管理-批量删除")
    @RequiresPermissions("system:user:remove")
    @DeleteMapping(value = "/deleteBatch")
    @ResponseBody
    public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
        try
        {
            sysUserService.removeByIds(Arrays.asList(ids.split(",")));
            return Result.ok("批量删除成功！");
        }
        catch (Exception e)
        {
            return Result.error(e.getMessage());
        }

    }

    @RequiresPermissions("system:user:resetPwd")
    @AutoLog(value = "用户管理-重置密码", operateType = 3)
    @GetMapping("/resetPwd/{userId}")
    public String resetPwd(@PathVariable("userId") String userId, ModelMap mmap)
    {
        mmap.put("user", sysUserService.getById(userId));
        return prefix + "/resetPwd";
    }

    @RequiresPermissions("system:user:resetPwd")
    @AutoLog(value = "用户管理-重置密码", operateType = 3)
    @PostMapping("/resetPwd")
    @ResponseBody
    public Result<?> resetPwdSave(SysUser user)
    {
        sysUserService.checkUserAllowed(user);
        SysUser u = this.sysUserService.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUsername, user.getUsername()));
        if (u == null) {
            return Result.error("用户不存在！");
        }
        user.setId(u.getId());
        return sysUserService.changePassword(user);
    }

    /**
     * 进入授权角色页
     */
    @GetMapping("/authRole/{userId}")
    public String authRole(@PathVariable("userId") String userId, ModelMap mmap)
    {
        SysUser user = sysUserService.getById(userId);
        // 获取用户所属的角色列表
        List<SysUserRole> userRoles = userRoleService.selectUserRoleByUserId(userId);
        mmap.put("user", user);
        mmap.put("userRoles", userRoles);
        return prefix + "/authRole";
    }

    /**
     * 用户授权角色
     */
    @RequiresPermissions("system:user:add")
    @AutoLog(value = "用户管理-用户授权角色", operateType = 3)
    @PostMapping("/authRole/insertAuthRole")
    @ResponseBody
    public Result<?> insertAuthRole(String userId, String[] roleIds)
    {
        sysUserService.insertUserAuth(userId, roleIds);
        return Result.ok("授权成功！");
    }

    /**
     * 校验用户名
     */
    @PostMapping("/checkUserNameUnique")
    @ResponseBody
    public String checkUserNameUnique(SysUser user)
    {
        return sysUserService.checkUserNameUnique(user.getUsername());
    }

    /**
     * 校验手机号码
     */
    @PostMapping("/checkPhoneUnique")
    @ResponseBody
    public String checkPhoneUnique(SysUser user)
    {
        return sysUserService.checkPhoneUnique(user);
    }

//    /**
//     * 校验email邮箱
//     */
//    @PostMapping("/checkUnique")
//    @ResponseBody
//    public String checkEmailUnique(SysUser user)
//    {
//        return sysUserService.checkEmailUnique(user);
//    }

}
